<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="试卷的名称" prop="paperNama">
        <el-input
          v-model="queryParams.paperNama"
          placeholder="请输入试卷的名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="papersList"
    >
      <el-table-column label="试卷的名称" align="center" prop="paperNama" />
      <el-table-column label="试卷的总分值" align="center" prop="totalScored" />
      <el-table-column label="时间限制(分钟)" align="center" prop="timeLimit" />
      <el-table-column label="试卷得分值" align="center" prop="totalScore">
        <template slot-scope="scope">
          <span>{{
            scope.row.totalScore == 0 ? "-" : scope.row.totalScore
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所用时间(分钟)" align="center" prop="timeTaken">
        <template slot-scope="scope">
          <span>
            {{ scope.row.timeTaken == 0 ? "-" : scope.row.timeTaken }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="onclick(scope.row)"
            v-hasPermi="['papers:papers:edit']"
            v-if="scope.row.totalScore == 0"
            >去考试</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.totalScore != 0"
            v-hasPermi="['papers:papers:edit']"
            >查看考试成绩</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['papers:papers:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['papers:papers:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷作业对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!--        <el-form-item label="课程id" prop="courseId">-->
        <!--          <el-input v-model="form.courseId" placeholder="请输入课程id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="试卷的名称" prop="nama">
          <el-input v-model="form.nama" placeholder="请输入试卷的名称" />
        </el-form-item>
        <el-form-item label="试卷的总分值" prop="totalScored">
          <el-input
            v-model="form.totalScored"
            placeholder="请输入试卷的总分值"
          />
        </el-form-item>
        <el-form-item label="时间限制" prop="timeLimit">
          <el-input
            v-model="form.timeLimit"
            placeholder="请输入完成试卷的时间限制"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 去考试 -->
    <el-dialog
      title="考试"
      :visible.sync="testPaperState"
      width="800px"
      append-to-body
    >
      <p style="text-align: center">
        {{ testPaper.nama }} （总分：{{ testPaper.totalScored }}）（时间：{{
          testPaper.timeLimit
        }}分钟）
      </p>
      <el-statistic
        ref="statistic"
        @finish="hilarity"
        @change="atAnytime"
        format="mm:ss"
        :value="deadline4"
        title="考试剩余时间(分钟)："
        time-indices
      >
      </el-statistic>
      <!-- type 1 ‘主观题’ 2 '单选题' 3 '填空题' 4 '多选题'-->
      <div
        class="item"
        v-for="(item, index) in testPaper.questionList"
        :key="index"
      >
        <p>{{ index + 1 }} 、 {{ item.content }}? （{{ item.score }}分数）</p>
        <el-input
          v-if="item.type == '1'"
          type="textarea"
          resize="none"
          v-model="item.value"
          placeholder="请输入内容"
        ></el-input>
        <el-radio-group v-else-if="item.type == '2'" v-model="item.value">
          <el-radio
            v-for="(option, index) in item.optionsList"
            :key="option.optionId"
            :label="option.optionId"
          >
            {{ option.content }}
          </el-radio>
        </el-radio-group>
        <el-input
          v-else-if="item.type == '3'"
          v-model="item.value"
          placeholder="请输入"
        ></el-input>
        <el-checkbox-group v-else v-model="item.value">
          <el-checkbox
            :label="option.optionId"
            v-for="option in item.optionsList"
            >{{ option.content }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <!-- 按钮 -->
      <div style="margin-top: 10px; text-align: right">
        <el-button @click="paperCancel()">取消</el-button>
        <el-button @click="paperSure()" type="primary">提交</el-button>
      </div>
    </el-dialog>

    <!-- 试卷详情 -->
    <el-dialog
      title="考试"
      :visible.sync="testState"
      width="800px"
      append-to-body
    >
      <p style="text-align: center">
        {{ ywPapers.nama }} （总分：{{ ywPapers.totalScored }}）（时间：{{
          ywPapers.timeLimit
        }}分钟）
      </p>
      <!-- type 1 ‘主观题’ 2 '单选题' 3 '填空题' 4 '多选题'-->
      <div
        class="item"
        v-for="(item, index) in paperStudentAnswersList"
        :key="index"
      >
        <p>
          {{ index + 1 }} 、 {{ item.questionContent }}? （{{
            item.questionScore
          }}分数）{{ (item.questionType == '1' || item.questionType == '3') ? "待定" : item.isCorrect == '1' ? "正确" : "错误"  }}
        </p>
        <el-input
          v-if="item.questionType == '1'"
          type="textarea"
          resize="none"
          v-model="item.value"
          placeholder="请输入内容"
          disabled
        ></el-input>
        <el-radio-group
          v-else-if="item.questionType == '2'"
          v-model="item.value"
          disabled
        >
          <el-radio
            v-for="(option, index) in item.optionsList"
            :key="option.optionId"
            :label="option.optionId"
          >
            {{ option.content }}
          </el-radio>
        </el-radio-group>
        <el-input
          v-else-if="item.questionType == '3'"
          v-model="item.value"
          placeholder="请输入"
          disabled
        ></el-input>
        <el-checkbox-group v-else v-model="item.value" disabled>
          <el-checkbox
            :label="option.optionId"
            v-for="option in item.optionsList"
            >{{ option.content }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <!-- 按钮 -->
      <div style="margin-top: 10px; text-align: right">
        <!-- <el-button @click="paperCancel()">取消</el-button> -->
        <el-button @click="testState = false" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPapers,
  delPapers,
  addPapers,
  updatePapers,
} from "@/api/papers/papers";

import {
  getPapersInfo,
  selectPapersByUserId,
  submitTest,
  getInfoBack,
} from "@/api/examination/examination";
export default {
  name: "Papers",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷作业表格数据
      papersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperNama: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nama: [
          { required: true, message: "试卷的名称不能为空", trigger: "blur" },
        ],
      },

      // 试卷详情
      testPaperState: false,
      testPaper: {},
      deadline4: null,
      resultId: "",
      CountdownTime: null,

      // 考试完成
      testState: false,
      paperStudentAnswersList: [],
      ywPapers: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询试卷作业列表 */
    getList() {
      this.loading = true;
      selectPapersByUserId(this.queryParams).then((response) => {
        this.papersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paperId: null,
        nama: null,
        totalScored: null,
        timeLimit: null,
        courseId: null,
        active: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 考试完成后的查看详情 */
    handleUpdate(row) {
      getInfoBack({paperId:row.paperId}).then((res) => {
        this.testState = true;
        this.ywPapers = res.data.ywPapers;

        // 线根据 questionId 问题ID对返回数组进行去重
        const uniqueArray = res.data.paperStudentAnswersList.reduce(
          (acc, current) => {
            const x = acc.find(
              (item) => item.questionId === current.questionId
            );
            if (!x) {
              return acc.concat([current]);
            } else {
              return acc;
            }
          },
          []
        );

        let arr = [];
        for (let i = 0; i < uniqueArray.length; i++) {
          let element = uniqueArray[i];
          if (element.questionType === "4") {
            let xuan = [];
            for (let j = 0; j < res.data.paperStudentAnswersList.length; j++) {
              let nav = res.data.paperStudentAnswersList[j];
              if (nav.questionId === element.questionId) {
                xuan.push(nav.optionId);
              }
            }
            arr.push({
              ...element,
              value: xuan,
            });
          } else if (element.questionType === "2") {
            arr.push({ ...element, value: element.optionId });
          } else {
            arr.push({ ...element, value: element.answerText });
          }
        }
        // 判断多选题，是否正确
        for (let n = 0; n < arr.length; n++) {
          let content = arr[n];
          if (content.questionType == "4") {
            for (let index = 0; index < content.value.length; index++) {
              let kroi = content.value[index];
              for (let k = 0; k < content.optionsList.length; k++) {
                if (
                  kroi == content.optionsList[k].optionId &&
                  content.optionsList[k].isCorrect == "2"
                ) {
                  content.isCorrect = "2";
                  return false;
                }
              }
            }
          }
        }
        this.paperStudentAnswersList = arr;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.paperId != null) {
            updatePapers(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPapers(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperIds = row.paperId || this.ids;
      this.$modal
        .confirm('是否确认删除试卷作业编号为"' + paperIds + '"的数据项？')
        .then(function () {
          return delPapers(paperIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "papers/papers/export",
        {
          ...this.queryParams,
        },
        `papers_${new Date().getTime()}.xlsx`
      );
    },
    /** 去考试 */
    onclick(row) {
      this.resultId = row.resultId;
      this.$alert(
        "考试开始后，会进入倒计时，倒计时结束后会自动提交，请注意答题时间",
        "去考试",
        {
          confirmButtonText: "确定",
          callback: (action) => {
            getPapersInfo(row.paperId).then((res) => {
              if (res.code == 200) {
                this.testPaper = res.data;
                this.testPaperState = true;
                this.testPaper.questionList = res.data.questionList.map(
                  (element) => {
                    return {
                      ...element,
                      value: element.type === "4" ? [] : "",
                    };
                  }
                );
                this.deadline4 =
                  Date.now() + Number(res.data.timeLimit) * 60 * 1000;
              } else {
                this.$modal.msgError(res.msg);
              }
            });
          },
        }
      );
    },
    hilarity() {
      this.$notify({
        title: "提示",
        message: "时间已到",
        duration: 0,
      });
      this.SubmitPaper()
    },
    paperCancel() {
      this.$alert("取消考试你全部的回答将会消失", "取消考试", {
        confirmButtonText: "确定",
        callback: (action) => {
          this.testPaperState = false;
        },
      });
    },
    paperSure() {
      for (let i = 0; i < this.testPaper.questionList.length; i++) {
        let element = this.testPaper.questionList[i];
        if (element.type === "4" && element.value.length === 0) {
          this.$alert("您还有未完成的题目，你确定要提交吗？", "考试结束", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return false;
        } else if (element.type !== "4" && element.value === "") {
          this.$alert("您还有未完成的题目，你确定要提交吗？", "考试结束", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return false;
        }
      }

      this.SubmitPaper();
    },
    // 提交试卷
    SubmitPaper() {
      this.$refs.statistic.suspend(true); // 暂停倒计时
      let obj = {
        resultId: this.resultId,
        paperId: this.testPaper.paperId, // 试卷ID
        timeTaken: "", // 所用时间（分钟）
        paperStudentAnswersList: [],
      };
      let time = this.testPaper.timeLimit * 1000 * 60 - this.CountdownTime;
      obj.timeTaken = Math.ceil(time / 60000);
      for (let i = 0; i < this.testPaper.questionList.length; i++) {
        let element = this.testPaper.questionList[i];
        if (element.type === "2") {
          element.optionsList.forEach((item) => {
            if (item.optionId == element.value) {
              obj.paperStudentAnswersList.push({
                questionId: element.questionId, // 题目ID
                paperId: this.testPaper.paperId, // 试卷ID
                optionId: element.value, // 选项id
                score: element.score, // 此题分数
                isCorrect: item.isCorrect, // 答案是否正确(1正确 2不正确 3待定)
              });
            }
          });
        } else if (element.type === "1") {
          obj.paperStudentAnswersList.push({
            questionId: element.questionId, // 题目ID
            paperId: this.testPaper.paperId, // 试卷ID
            answerText: element.value, // 学生答案
            score: element.score, // 此题分数
            isCorrect: 3, // 答案是否正确(1正确 2不正确 3待定)
          });
        } else if (element.type === "3") {
          element.optionsList.forEach((item) => {
            obj.paperStudentAnswersList.push({
              questionId: element.questionId, // 题目ID
              paperId: this.testPaper.paperId, // 试卷ID
              answerText: element.value, // 学生答案
              score: element.score, // 此题分数
              isCorrect: 3, // 答案是否正确(1正确 2不正确 3待定)
            });
          });
        } else if (element.type === "4") {
          for (let j = 0; j < element.value.length; j++) {
            let nav = element.value[j];
            for (let k = 0; k < element.optionsList.length; k++) {
              if (nav === element.optionsList[k].optionId) {
                obj.paperStudentAnswersList.push({
                  questionId: element.questionId, // 题目ID
                  paperId: this.testPaper.paperId, // 试卷ID
                  optionId: nav, // 选项id
                  score: element.score, // 此题分数
                  isCorrect: element.optionsList[k].isCorrect, // 答案是否正确(1正确 2不正确 3待定)
                });
              }
            }
          }
        }
      }
      submitTest(obj).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "提交成功",
            type: "success",
          });
          this.testPaperState = false;
          this.getList();
        } else {
          this.$message({
            message: "提交失败",
            type: "error",
          });
        }
      });
    },
    atAnytime(e) {
      this.CountdownTime = e;
    },
  },
};
</script>
